import {  constantRoutes } from '@/router'
import { getRoutes } from '@/api/role' // 获取路由的接口方法
import Layout from "@/layout"

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  // if(route.path == "/index"){
  //   return true
  // }
  if(!route.available){
    return false
  }
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}


/**
 * 把后台返回菜单组装成routes要求的格式
 * @param {*} routes
 */
export function getAsyncRoutes(routes) {
  const res = []
  const keys = ['path', 'name', 'children', 'redirect', 'alwaysShow', 'meta', 'hidden', 'available', 'url']
  routes.forEach(item => {
    const newItem = {}
    item.meta = {};
    if (item.component) {
      if (item.component === 'layout/Layout') {
        newItem.component = Layout
      } else {
        // newItem.component = () => import(`@/${item.component}`)
          if(item.component != null){
            newItem.component = (resolve) => require([`@/${item.component}`], resolve)
          }
      }
    }
    if(!item.component && item.children.length > 0){
      newItem.component = {
        render: h => h("router-view")
      }
    }
    for (const key in item) {
      if (keys.includes(key)) {
        //拼接meta元素
        if(key == "meta"){
          newItem.meta ={
            authority: [item.permission],
            icon : item.icon,
            title : item.name,
            roles : item.roles
          };
        }else{
          newItem[key] = item[key]
        }
      }
    }
    if (newItem.children && newItem.children.length) {
      newItem.children = getAsyncRoutes(item.children)
    }
    res.push(newItem)
  })
  return res
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  async generateRoutes({ commit }, roles) {
    const routes = await getRoutes() // 获取到后台路由
    return new Promise( resolve => {
      let accessedRoutes
      const asyncRoutes = getAsyncRoutes(routes.data.data) // 对路由格式进行处理
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        //所有用户验证权限
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
